package connectfour;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

public class PersistPlayerServlet extends HttpServlet{
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		MemcacheService mc = MemcacheServiceFactory.getMemcacheService();
		
		
		Player p = null;
		
		p = pm.getObjectById(Player.class, KeyFactory.stringToKey(req.getParameter("pKey")));
		
		int set = Integer.parseInt(req.getParameter("status"));
		
		// set status
		if(set == 0){
			p.setStatus(0);
		}
		else if(set == 1){
			p.setStatus(1);
		}
		else if(set == 2){
			p.setStatus(2);
		}
		
		// increment wins
		set = Integer.parseInt(req.getParameter("wins"));
		if(set == 1){
			p.incWins();
		}
		
		// increment losses
		set = Integer.parseInt(req.getParameter("losses"));
		if(set == 1){
			p.incLosses();
		}
		
		// set ratio
		set = Integer.parseInt(req.getParameter("ratio"));
		if(set == 1){
			p.setRatio();
		}
		
		Transaction tx = pm.currentTransaction();
		
		try{
			tx.begin();
	
			pm.makePersistent(p);
			
			tx.commit();
		}finally{
			if(tx.isActive()){
				tx.rollback();
			}
			pm.close();
		}
	}
}
